package com.namecard.namecardapi.util;

import com.namecard.namecardapi.exception.BusinessException;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * @author wzx
 */
public class TokenUtil {

    /**
     * 获取token，将传递的数据封装进JWT的荷载中
     * eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIyMDE3MTExMTEzNSIsImV4cCI6MTcyNjQxNjQ3MX0.9_r9k-WyQ-RDi1chFhSmZKu0A7wUfLjRTEhOPfhdGm0
     */
    public static String getToken(String userId){
        if (userId == null){return null;}
        JwtBuilder jwtBuilder = Jwts.builder();
        return jwtBuilder
                        .setHeaderParam("typ", "JWT")
                        .setHeaderParam("alg", "HS256")
                        .claim("userId", userId)
                        .setExpiration(new Date(System.currentTimeMillis() + Constants.TOKEN_INVALID_TIME))
                        .signWith(SignatureAlgorithm.HS256, Constants.TOKEN_SECRET)
                        .compact();
    }

    /**
     * 解密Token，拿到内部封装的userId数据
     */
    public static String getUserIdFromToken(String token){
        JwtParser jwtParser = Jwts.parser();
        // 通过签名对Token进行解析，得到的结果是一个类似集合的封装类
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constants.TOKEN_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("userId").toString();
    }
    public static String getUserId(String token) throws BusinessException {
        String userId;
        if (token == null) {
            throw new BusinessException(403, "用户未登录");
        }
        try {
            userId = TokenUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            throw new BusinessException(403, "用户未登录");
        }
        return userId;
    }
}
